<template>
  <div class="row">
    <div class="col-sm-12 col-md-8">
      <!--new pizza-->
      <NewPizza></NewPizza>
    </div>
    <div class="col-sm-12 col-md-4">
      <!--品种展示-->
      <h3 class="text-muted my-5">菜单</h3>
      <table class="table">
        <thead class="table table-default">
          <tr>
            <th>品种</th>
            <th>删除</th>
          </tr>
        </thead>
        <tbody v-for="item in getMenuItems" :key="item.name">
          <tr>
            <td>{{item.name}}</td>
            <td>
              <button @click="deleteData(item)" class="btn btn-outline-danger btn-sam">&times;</button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script>
import NewPizza from "./NewPizza";
export default {
  data() {
    return {
      // getMenuItem: [],
    };
  },
  components: {
    NewPizza,
  },
  computed: {
    //转换成对象
    getMenuItems: {
      //在vuex中获取数据
      get() {
        // return this.$store.state.menuItems;
        //2.通过getters获取数据
        return this.$store.getters.getMenuItems;
      },
      set() {},
    },
  },
  created() {
    fetch("拿到数据展示/menu.json")
      .then((res) => {
        return res.json();
      })
      .then((data) => {
        // console.log(data);
        let menuArray = [];
        for (let key in data) {
          data[key].id = key;
          menuArray.push(data[key]);
        }
        // this.getMenuItem = menuArray;

        //数据同步
        this.$store.commit("setMenuItems", menuArray);
      });
  },
  methods: {
    deleteData(item) {
      fetch("拿到数据展示/menu/" + item.id + "/.json", {
        method: "DELETE",
        headers: {
          "Content-type": "application/json",
        },
      })
        .then((res) => res.json())
        // .then(() => this.$router.push({ name: "menuLink" }));
        .then(() => this.$store.commit("removeMenuItems", item));
    },
  },

  // //组件内守卫
  // //进入页面时触发钩子
  // beforeRouteEnter: (to, from, next) => {
  //   //异步获取data数据（vm）
  //   next((vm) => {
  //     alert("Hello " + vm.name);
  //   });
  // },
  // //离开页面时触发钩子
  // beforeRouteLeave(to, from, next) {
  //   if (confirm("确定离开吗？") == true) {
  //     //询问是否离开==true
  //     next(); //确认离开
  //   } else {
  //     next(false); //false不离开
  //   }
  // },
};
</script>

<style scoped>
</style>
